<template>
  <div class="warpper">
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="auto" label-position="right">


        <el-form-item label="From Stock Code">
          <el-input v-model="searchForm.sku" placeholder="Enter Stock Code">
          </el-input>
        </el-form-item>
        <el-form-item label="Stock Code To">
          <el-input v-model="searchForm.skuto" placeholder="Enter Stock Code">
          </el-input>
        </el-form-item>

        <el-form-item label="From Customer lD" style="margin-left: 15px;">
          <el-input v-model="searchForm.customerid" placeholder="Enter Customer lD">
          </el-input>
        </el-form-item>
        <el-form-item label="Customer lD To">
          <el-input v-model="searchForm.customeridto" placeholder="Enter Customer lD">
          </el-input>
        </el-form-item>
        <br />

        <el-form-item label="From Salesperson">
          <el-input v-model="searchForm.salesperson" placeholder="Enter Salesperson">
          </el-input>
        </el-form-item>
        <el-form-item label="Salesperson To">
          <el-input v-model="searchForm.salespersonto" placeholder="Enter Salesperson">
          </el-input>
        </el-form-item>

        <el-form-item label="From Brand" style="margin-left: 15px;">
          <el-input v-model="searchForm.brand" placeholder="Enter Brand">
          </el-input>
        </el-form-item>
        <el-form-item label="Brand To">
          <el-input v-model="searchForm.brandto" placeholder="Enter Brand">
          </el-input>
        </el-form-item>
        <br />
        <el-form-item label="Created Time">
          <el-date-picker v-model="searchForm.created_at" type="datetimerange" range-separator="-"
            start-placeholder="Select Start Date" end-placeholder="Select End Date" value-format="MM-dd-yyyy"
            style="width: 133%;">
          </el-date-picker>
        </el-form-item>

        <br />
        <el-form-item>
          <el-button @click="find()" plain>Search</el-button>
          <el-button type="primary" plain @click="convertExcelToPDF()">Print Report</el-button>
          <el-button type="primary" plain @click="exportData">Export to Excel</el-button>
        </el-form-item>


      </el-form>
    </div>
    <div class="table">
      <el-table :data="tableData" size="small" stripe border style="width: 100%" row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">

        <el-table-column type="selection" width="50" align="center" />

        <el-table-column prop="createdTime" label="Date" min-width="120" sortable align="center">
          <template v-slot="scope">
            <span>{{ scope.row.created_at}}</span>
          </template>
        </el-table-column>

        <el-table-column label="Stock Code&refno" min-width="130" align="center">
          <template v-slot="scope">
            <span v-if="scope.row.sku">{{scope.row.sku}}</span>
          </template>
        </el-table-column>

        <el-table-column label="Stock Name&Customer Name" min-width="130" align="center">
          <template v-slot="scope">
            <span v-if="scope.row.name">{{scope.row.name}}</span>
          </template>
        </el-table-column>

        <el-table-column label="S'P" min-width="130" align="center">
          <template v-slot="scope">
            <span>{{scope.row.staff}}</span>
          </template>
        </el-table-column>

        <el-table-column label="Unit" width="140" align="center">
          <template v-slot="scope">
            <span>{{scope.row.qty}}{{scope.row.unit}}</span>
          </template>
        </el-table-column>

        <el-table-column label="U.Cost/U.price" width="140" align="center">
          <template v-slot="scope">
            <span>{{scope.row.costprice}}</span>
          </template>
        </el-table-column>


        <el-table-column label="Discount%" width="140" align="center">
          <template v-slot="scope">
            <span></span>
          </template>
        </el-table-column>

        <el-table-column label="Total Amt" width="140" align="center">
          <template v-slot="scope">
            <span>{{scope.row.costamount}}</span>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <div class="page">
      <el-pagination v-if="isPaginate" background :current-page="page.current_page" :page-sizes="page.sizes"
        :page-size="page.per_page" layout="prev, pager, next" :total="page.total" @size-change="sizeChange"
        @current-change="currentChange" />
    </div>
  </div>
</template>

<script>
  import CURD from "@/mixin/CURD";
  import {
    jsPDF
  } from 'jspdf';
  import {
    exportData as exceldata
  } from "@/api/product";
  import {
    index as warehouselist
  } from "@/api/warehouse";
  export default {
    name: "customerIndex",
    mixins: [CURD],
    data() {
      return {
        mydate: '',
        formData: {},
        module: "product",
        newTitle: "New inventory",
        editTitle: "Edit inventory",
        isPaginate: true,
        isUploadFile: false,
        fileReader: new FileReader(),
        isShow: false,
        imageUrl: "",
        group: [],
        warehouse: [],
        deptOptions: [],
        searchForm: {
          type: 1
        },

      };
    },
    async created() {
      const today = new Date();
      this.mydate = today
      try {
        const {
          data
        } = await warehouselist(1, 100);
        this.warehouse = data;
      } catch (error) {
        console.error('Failed to fetch warehouse:', error);
      }
      this.feachData();
    },
    methods: {
      adata() {
        const currentDate = new Date();
        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
        const day = String(currentDate.getDate()).padStart(2, '0');
        const hours = String(currentDate.getHours()).padStart(2, '0');
        const minutes = String(currentDate.getMinutes()).padStart(2, '0');
        const seconds = String(currentDate.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      async fetchData() {
        this.searchForm.type = 1
        let {
          index
        } = require(`@/api/product`);
        const res = await index(
          this.page.current_page,
          this.page.per_page,
          this.searchForm
        );
        if (
          res.data instanceof Object &&
          typeof this.transfromData === "function"
        ) {
          let data = this.transfromData(res.data);
          this.tableData = data;
        } else {
          this.tableData = res.data;
        }

        let result = this.tableData; // 假设 data 是你原始的数组
        for (let i = 0; i < result.length; i++) {
          result[i].created_at = i + 1;
          result[i].costamount = ""
          let costamount = 0;
          for (let v = 0; v < result[i].children.length; v++) {
            result[i].children[v].sku = result[i].children[v].ordernumber;
            result[i].children[v].name = result[i].children[v].customername;
            costamount += result[i].children[v].costamount;
          }
          //result[i].costamount = (costamount).toFixed(2);
          if (result[i].children.length > 0) {
            var aar = {};
            aar.created_at = "Total"
            aar.id = ""
            aar.cname = ""
            aar.currency = ""
            aar.rate = ""
            aar.costamount = (costamount).toFixed(2);


            result[i].children.push(aar);
          }

        }
        this.tableData = result

        let {
          rules
        } = require(`@/model/product`);
        this.rules = rules;
        if (res.meta) {
          // 分页
          res.meta.per_page = parseInt(res.meta.per_page);
          this.page = Object.assign(this.page, res.meta);
        } else {
          this.isPaginate = false; // 不分页
        }
      },
      parseOrOne(input) {
        const result = parseFloat(input);
        if (isNaN(result)) {
          return 1.0;
        }
        return result;
      },
      async convertExcelToPDF() {

        var that = this
        this.searchForm.type = 9
        const resv = await exceldata(
          this.page.current_page,
          this.page.per_page,
          this.searchForm);
        const file = new Blob([resv], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        // 读取 Excel 文件
        const reader = new FileReader();
        reader.onload = function(e) {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, {
            type: 'array'
          });

          // 假设只处理第一个 Sheet
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];

          // 将 Sheet 转换为 HTML
          const htmlString = XLSX.utils.sheet_to_html(worksheet);
          const div = document.createElement('div');
          div.innerHTML = htmlString;
          div.style.width = '800px'; // 设置一个足够宽的宽度，以确保内容不会被截断
          div.style.transform = 'scale(0.7)'; // 根据需要调整缩放比例
          div.style.transformOrigin = 'top left'; // 设置变换的原点
          document.body.appendChild(div);

          // 使用 html2canvas 和 jsPDF 转换 HTML 为 PDF
          html2canvas(div).then(canvas => {
            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF();
            pdf.addImage(imgData, 'PNG', 0, 0);
            pdf.save('Stock Detailed Sales Report_' + that.adata() + '.pdf');
            document.body.removeChild(div); // 清理 DOM
          });
        };
        reader.readAsArrayBuffer(file);
      },
      async exportData() {
        this.searchForm.type = 9
        console.log(this.page.current_page, this.page.per_page)
        const resv = await exceldata(
          this.page.current_page,
          this.page.per_page,
          this.searchForm);
        this.exportFile('Stock Detailed Sales Report_' + this.adata() + '.xlsx', resv);
      },
      exportFile(fileName, res) {
        const content = res;
        const blob = new Blob([content], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = window.URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          window.URL.revokeObjectURL(elink.href); // 释放 URL对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          window.navigator.msSaveBlob(blob, fileName);
        }
      },
      parseDateStr(dateStr) {
        const [month, day, year] = dateStr.split('-').map(Number);
        return new Date(year, month - 1, day);
      },
      transfromData(data) {
        let result = data.map((item) => {
          item.isEdit = false;
          return item;
        });
        return result;
      },
    }

  }
</script>
<style>
  .customWidth {
    width: 80%;
  }
</style>
<style>
  .table,
  .toolbar,
  .page {
    margin: 20px;
  }

  .toolbar {
    margin-top: 10px;
    padding: 5px;
  }

  .table {
    margin-bottom: 10px;
  }

  .page {
    margin-top: 10px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }

  .green-text {
    color: green;
  }

  .red-text {
    color: red;
  }

  .yellow-text {
    color: yellow;
  }
</style>